package com.motion.provider;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.motion.result.ResultFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;

@Component
public class OSSProvider {
    @Value("${aliyun.endpoint}")
    private String endpoint;

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.bucketName1}")
    private String bucketName1;
    /*
    @Value("${aliyun.bucketName}")
    private String bucketName2;
    @Value("${aliyun.bucketName}")
    private String bucketName3;*/


    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    public String fileUpload(InputStream fileStream, String fileName,int type) {
        // 创建OSSClient实例。
        String bucketName=null;
        switch (type) {
            case 1:
                bucketName = bucketName1;
                break;
                /*
            case 2:
                bucketName =bucketName2;
                break;
            case 3:
                bucketName=bucketName3;
                break;

                 */
        }
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName, fileName, fileStream);
            // 设置URL过期时间为1年。3600 * 1000 * 24 * 365
            // 时间暂时设置为100年
            Date expiration = new Date(new Date().getTime() + 3600 * 1000 * 24 * 36500L);
            // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
            URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
            return url.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
//        throw new BusinessException(ResultFactory.buildFailResult("上传出错"));
        return "";
    }

}
